﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SFast.DB;
using SolutionBLL;
using SolutionModel;
using SFast;

namespace MvcUI.Areas.AdminWeb.Controllers.AdminSystem
{
    public class RoleController : Controller
    {
        //
        // GET: /AdminWeb/Role/

        #region Index
        public ActionResult Index()
        {
            return View();
        }
        #endregion

        #region 编辑、编辑保存
        //编辑加载 
        public ActionResult edit()
        {
            return View((object)"edit");
        }

        //编辑保存
        public JsonResult editSave(T_AdminRole obj)
        {
            MessageInfoByFormModel mss = new MessageInfoByFormModel();
            try
            {
                T_AdminRolesBLL bll = new T_AdminRolesBLL();
                var rs = bll.HasRolesName(obj.RoleName, obj.RoleID);
                if (rs > 0)
                {
                    throw new Exception("角色名称不可用或数据库中已存在。");
                }
                bll.UpdateAdminRoles(obj);
                mss.info = "角色保存成功！";
                mss.status = "y";
                return Json(mss);
            }
            catch (Exception emsg)
            {
                mss.info = emsg.Message;
                mss.status = "n";
                return Json(mss);
            }
        }
        #endregion

        #region 创建角色加载、保存事件
        //添加加载 
        public ActionResult add()
        {
            return View("edit",(object)"add");
        }

        //添加保存
        public JsonResult addSave(T_AdminRole obj)
        {
            MessageInfoByFormModel mss = new MessageInfoByFormModel();
            try
            {
                T_AdminRolesBLL bll = new T_AdminRolesBLL();
                obj.RoleID = Guid.NewGuid().ToString();
                obj.CreateTime = DateTime.Now;
                //添加前检查当前在添加的角色名称是否已经存在
                int re = bll.HasRolesName(obj.RoleName, "");
                if (re > 0)
                {
                    mss.info = "对不起，角色名称不可用，可能在数据中已经存在！";
                    mss.status = "n";
                }

                //添加用户
                bll.InsertAdminRoles(obj);
                mss.info = "添加新角色成功！";
                mss.status = "y";
                return Json(mss);
            }
            catch (Exception emsg)
            {
                mss.info = emsg.Message;
                mss.status = "n";
                return Json(mss);
            }
        }
        #endregion

        #region Dialog  弹出
        public ActionResult Dialog()
        {
            return View();
        }
        #endregion

        #region verifyName  验证角色名称
        public String verifyName()
        {
            T_AdminRolesBLL bll = new T_AdminRolesBLL();
            String Account = Request["param"];
            String id = Request.QueryString["id"];
            int rs = bll.HasRolesName(Account, id);
            if (rs > 0)
            {
                return "对不起，此角色不可用或已存在！";
            }
            else
            {
                return "y";
            }
        }
        #endregion

        #region AllRoles 只获取状态为可用的角色信息
        /// <summary>
        /// 只获取状态为可用的角色信息
        /// </summary>
        /// <param name="Disabled"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public JsonResult AllRoles(Boolean Disabled,String key=null)
        {
            T_AdminRolesBLL bll = new T_AdminRolesBLL();
            
            List<T_AdminRole> roles = bll.Get_AdminRolesList_By_IsDisabled(Disabled,key);
            return Json(roles, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region RolesRelated 获取所有角色信息(包含菜单关系)
        /// <summary>
        ///  获取所有角色信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public JsonResult RolesRelated(String key)
        {
            T_AdminRolesBLL bll = new T_AdminRolesBLL();
            List<T_AdminRole> list = bll.GetAdminRolesList(key);
            return Json(list);
        }
        #endregion

        #region getUser 通过角色ID+关键词查询用户
        /// <summary>
        /// 通过角色ID+关键词查询用户
        /// </summary>
        /// <param name="rid">角色ID</param>
        /// <param name="key">关键词</param>
        /// <returns></returns>
        public JsonResult getUser(String rid,String key)
        {
            T_UsersInRolesBLL uir = new T_UsersInRolesBLL();
            List<T_AdminUser> users= uir.getUserByRoleID(rid,key);
            return Json(users);
        }
        #endregion

        #region getTree 获取所有菜单
        public JsonResult getTree()
        {
            T_MenuBLL bll = new T_MenuBLL();
            List<T_Menu> menu = bll.getAllTree();
            List<EasyTreeModel> list = new List<EasyTreeModel>();
            menu.ForEach(o =>
            {
                EasyTreeModel model = new EasyTreeModel();
                model.id = o.C_ID;
                model.text = o.C_Name;
                model.pid = (int)o.C_Parent_ID;
                model.url = o.C_Url;
                list.Add(model);
            });

            list.ForEach(o =>
            {
                o.children = list.Where(l => l.pid == o.id).ToList();
            });
            var q = list.Where(o => o.pid == 0);
            return Json(q);
        }
        #endregion

        #region 更新角色菜单权限
        /// <summary>
        /// 更新角色菜单权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="menuIds"></param>
        /// <returns></returns>
        public JsonResult updateMenu(String roleId, String menuIds)
        {
            MessageInfoByFormModel mesInfo = new MessageInfoByFormModel();

            if (!roleId._HasVal())
            {
                mesInfo.info = "角色ID不可为空！";
                mesInfo.status = "y";
                return Json(mesInfo);
            }
            List<int> list_menuIds = new List<int>();
            menuIds = menuIds.TrimEnd(',');
            if (menuIds._HasVal())
            {
                menuIds.Split(',').ForEach(o =>
                {
                    list_menuIds.Add(Convert.ToInt32(o));
                });
            }
            T_MenuInRoleBLL mirbll = new T_MenuInRoleBLL();
            //保存信息
            mirbll.InsertOrUpdate(roleId, list_menuIds);
            mesInfo.info = "角色菜单权限已更新！";
            mesInfo.status = "y";
            return Json(mesInfo);
        }
        #endregion

        public JsonResult addUser(String roleId, String userIds)
        {
            T_UsersInRolesBLL bll = new T_UsersInRolesBLL();
            MessageInfoByFormModel mim = new MessageInfoByFormModel();
            int r = bll.addUserForRole(roleId, userIds);
            if (r > 0)
            {
                mim.info = "用户添加完成！";
                mim.status = "y";
            }
            else
            {
                mim.info = "用户添加失败！请重试或联系管理员！";
                mim.status = "n";
            }
            return Json(mim);
        }

        public JsonResult deleteUser(String roleid ,String userIds)
        {
            T_UsersInRolesBLL bll = new T_UsersInRolesBLL();
            MessageInfoByFormModel mim = new MessageInfoByFormModel();

            int r = bll.deleteUserInRole(roleid,userIds);
            if (r > 0)
            {
                mim.info = "删除用户成功！";
                mim.status = "y";
            }
            else
            {
                mim.info = "删除用户失败！请重试或联系管理员！";
                mim.status = "n";
            }
            return Json(mim);
        }
    }
}
